import {Upload, message} from 'antd';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import React, {useState} from 'react';
import {downloadFileUrl, uploadFile} from "@/services/system/file";

interface AvatarViewProps {
  avatar: string;
  onChange: (url: string) => void;
}

const AvatarView: React.FC<AvatarViewProps> = ({avatar, onChange}) => {
  const [loading, setLoading] = useState(false);

  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange = async (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      try {
        const {data} = await uploadFile(info.file.originFileObj);
        console.log("uploadFile", data)
        onChange(data.id);
        message.success('头像上传成功');
      } catch (error) {
        message.error('头像上传失败');
      } finally {
        setLoading(false);
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div style={{marginTop: 8}}>上传头像</div>
    </div>
  );

  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {avatar ? (
        <img src={downloadFileUrl(avatar)} alt="avatar" style={{width: '100%'}}/>
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

export default AvatarView;
